<template>
    <el-table
          ref="tableRef"
          :data="paginatedTableData"
          style="width: 100%"
          class="layers-table"
        >
          <el-table-column label="名称" width="auto">
            <template #default="scope">
              <el-popover effect="light" trigger="hover" placement="top" width="auto">
                <template #default>
                  <div>名称: {{ scope.row.name }}</div>
                </template>
                <template #reference>
                  <el-text
                    tag="ins"
                    style="
                      font-size: 12px;
                      font-style: normal;
                      font-weight: 400;
                      line-height: 12px;
                      color: #2a78ff;
                      text-align: left;
                      text-decoration-line: underline;
                      text-transform: none;
                      text-wrap: nowrap;
                    "
                    >{{
                      scope.row.name.includes(':')
                        ? scope.row.name.substring(scope.row.name.indexOf(':') + 1)
                        : scope.row.name
                    }}</el-text
                  >
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="类型" prop="type"> </el-table-column>
          <el-table-column label="创建时间">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span style="margin-left: 10px">{{
                  scope.row.dateCreated ? dateFormat(scope.row.dateCreated) : ''
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="样式">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                {{ scope.row.defaultStyle?.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="136">
            <template #default="scope">
              <div class="layer-operation-button-area">
                <span class="operation-button" title="详情">
                  <img
                    src="@/assets/images/detail.png"
                    @click="handleDetailShow(scope.row)"
                  />
                </span>
                <span class="operation-button" title="切片设置">
                  <img
                    src="@/assets/images/layers/layer-catch-set.png"
                    @click="handleLayerCacheSet(scope.row)"
                  />
                </span>
                <span class="operation-button" title="删除" @click="handleDelete(scope.row)">
                  <img src="@/assets/images/delete.png" />
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="预览" width="360">
            <template #default="scope">
              <span
                style="
                  display: inline-block;
                  padding: 5px;
                  margin-right: 20px;
                  border: 1px dashed var(--el-table-border-color);
                  border-radius: 5px;
                "
              >
                <el-select
                  v-model="scope.row.previewType"
                  placeholder="请选择预览格式..."
                  size="small"
                  @change="showTypeChangeHandler($event, scope.row)"
                  style="width: 240px"
                >
                  <el-option-group
                    v-for="group in layerShowTypeOptions"
                    :key="group.label"
                    :label="group.label"
                  >
                    <el-option
                      v-for="item in group.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-option-group>
                </el-select>
                <el-button size="small" @click="layerPreview(scope.row)"> 预览 </el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="totalOrignTableData > 1"
          v-model:current-page="layersQueryFormData.pageNum"
          v-model:page-size="layersQueryFormData.pageSize"
          class="layers-pagination"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, total, sizes"
          :total="totalOrignTableData"
        />
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { dateFormat } from '@/utils/util'
import { fromLonLat } from 'ol/proj';
import { restHelperInstance } from '@/composables/useGeoHelper'
import { DICTIONARY } from '@/config/dictionary'
import useLayersFilterModal, { useLayerEditModal } from '../hooks'
import { computed, ref } from 'vue'
import type { ILayer } from 'geoserver-helper/interface'
import { geoserverConfig } from '@/config/geoserver';

interface emitInterface {
    (e: 'refresh', v: boolean): void
}

const emit = defineEmits<emitInterface>()
// 预览类型下拉框
const layerShowTypeOptions = DICTIONARY.previewTypeOptions

const tableRef = ref<InstanceType<typeof ElTable>>()
const layersFilterModal = useLayersFilterModal()
const layerEditModal = useLayerEditModal()
//查询出的原始数据(用于分页)
const orignTableData = layersFilterModal.orignTableData
// 数据总条数
const totalOrignTableData = layersFilterModal.totalOrignTableData
// 图层查询表单
const layersQueryFormData = layersFilterModal.layersQueryFormData
interface ExtendLayerInfo extends ILayer.LayerInfo {
  previewGroupType: string
  previewType: string
}
//分页数据
const paginatedTableData = computed<ExtendLayerInfo[]>(() => {
  return orignTableData.value
    .slice(
      (layersQueryFormData.value.pageNum - 1) * layersQueryFormData.value.pageSize,
      layersQueryFormData.value.pageNum * layersQueryFormData.value.pageSize,
    )
    .map((mapItem) => {
      const tempData = mapItem as ExtendLayerInfo
      restHelperInstance.getLayerInfoApi(mapItem.name).then((res) => {
        tempData.type = res.layer.type
        tempData.dateCreated = res.layer.dateCreated
        tempData.dateModified = res.layer.dateModified
        tempData.opaque = res.layer.opaque
        tempData.queryable = res.layer.queryable
        tempData.defaultStyle = res.layer.defaultStyle
        tempData.resource = res.layer.resource
      })
      tempData.previewType = ''
      tempData.previewGroupType = ''
      return tempData
    })
})

/**
 * @description: 查看图层详情
 * @param {*} row
 * @return {*}
 */
const handleDetailShow = (row: ILayer.LayerInfo) => {
  layerEditModal.currentEditLayer.value = row
  layerEditModal.detailVisible.value = true
}
/**
 * @description: 图层切片设置
 * @param {Layers.ResLayerListItem} row 当前图层
 * @return {*}
 */
 const handleLayerCacheSet = (row: ILayer.LayerInfo) => {
  layerEditModal.currentEditLayer.value = row
  layerEditModal.cacheSetVisible.value = true
}
/**
 * @description: 图层预览
 * @param {*} row
 * @return {*}
 */
 const layerPreview = async (row: ExtendLayerInfo) => {
  let layerExtent: number[] = []
  const resLayerInfo = await restHelperInstance.getLayerInfoApi(row.name)
  if (resLayerInfo.layer) {
    const queryUrl =
      geoserverConfig.url +
      resLayerInfo.layer.resource.href.substr(resLayerInfo.layer.resource.href.indexOf('/rest'))
      const res = await restHelperInstance.getLayerSourceInfoByHrefApi(queryUrl)
      if (res) {
        if (resLayerInfo.layer.type == 'VECTOR') {
          layerExtent = [
            res.featureType?.latLonBoundingBox?.minx as number,
            res.featureType?.latLonBoundingBox?.miny as number,
            res.featureType?.latLonBoundingBox?.maxx as number,
            res.featureType?.latLonBoundingBox?.maxy as number,
          ]
        } else if (resLayerInfo.layer.type == 'RASTER') {
          layerExtent = [
            res.coverage?.latLonBoundingBox.minx as number,
            res.coverage?.latLonBoundingBox.miny as number,
            res.coverage?.latLonBoundingBox.maxx as number,
            res.coverage?.latLonBoundingBox.maxy as number,
          ]
        }
      }
      // 获取浏览器窗口的宽度和高度
      const containerWidth = Math.floor(window.innerWidth * 0.8);
      const containerHeight = Math.floor(window.innerHeight * 0.8);


      // 计算地理范围的宽度和高度
      // 转换四至到EPSG:3857坐标系(经纬度的高宽比因为范围不一样会被拉伸)
      const minXY = fromLonLat([layerExtent[0], layerExtent[1]], "EPSG:3857");
      const maxXY = fromLonLat([layerExtent[2], layerExtent[3]], "EPSG:3857");
      const bboxWidth = Math.abs(maxXY[0] - minXY[0]);
      const bboxHeight = Math.abs(maxXY[1] - minXY[1]);

      // 计算地理范围的宽高比
      const bboxAspectRatio = bboxWidth / bboxHeight;

      // 根据容器的宽高比和地理范围的宽高比来计算width和height
      let mapWidth, mapHeight;
      if (containerWidth / containerHeight > bboxAspectRatio) {
        // 容器比地理范围更宽，因此我们需要根据高度来调整宽度
        mapHeight = Math.floor(containerHeight);
        mapWidth = Math.floor(mapHeight * bboxAspectRatio);
      } else {
        // 容器比地理范围更高，因此我们需要根据宽度来调整高度
        mapWidth = Math.floor(containerWidth);
        mapHeight = Math.floor(mapWidth / bboxAspectRatio);
      }
      let url = ''
      if (row.previewGroupType === 'WMS') {
        url = `${import.meta.env.VITE_MAP_SERVER_URL}/wms?service=WMS&version=1.1.0&request=GetMap&layers=${row.name}&styles=&bbox=${layerExtent.join(",")}&width=${mapWidth}&height=${mapHeight}&srs=EPSG:4326&format=${row.previewType}`
      } else if (row.previewGroupType === 'WFS') {
        url = `${import.meta.env.VITE_MAP_SERVER_URL}/wfs?service=WFS&version=1.0.0&request=GetFeature&maxFeatures=50&typeName=${row.name}&${row.previewType}`
      }
      window.open(url, '_blank')
  }
}

/**
 * @description: 删除图层
 * @param {*} row 待删除图层
 * @return {*}
 */
const handleDelete = (row: ILayer.LayerInfo) => {
  ElMessageBox.confirm('确认删除该图层么?', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const currentLayerName = row.name.includes(':') ? row.name.split(':')[1] : row.name
      const currentWorkspace = row.name.includes(':') ? row.name.split(':')[0] : ''
      restHelperInstance.deleteLayerApi(currentLayerName, currentWorkspace).then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        emit('refresh', false)
        // startQuery(true)
      })
    })
    .catch(() => {})
}

/**
 * @description: 预览类型改变事件
 * @param {*} row
 */
const showTypeChangeHandler = (selectValue: string, row: ExtendLayerInfo) => {
  const previewGroupItem = layerShowTypeOptions.find((groupItem) =>
    groupItem.options.some((optionItem) => optionItem.value === selectValue),
  )
  if (previewGroupItem) {
    row.previewGroupType = previewGroupItem.label
  }
}
const handleLayerEdit = (row: ILayer.LayerInfo) => {
    layerEditModal.currentEditLayer.value = row
}
</script>
<style scoped lang="scss">
@use './index';
</style>
